package com.biqee.service.tb.impl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.biqee.model.TaobaoShopParseResult;
import com.biqee.service.tb.TaobaoCShopRateParseService;
import com.biqee.util.JsoupUtil;

public class TaobaoCShopRateParseServiceImpl implements TaobaoCShopRateParseService {
	private static final Logger logger = Logger.getLogger(TbItemParseServiceImpl.class);
		
	@Override
	public void parse(Document doc, TaobaoShopParseResult result) {
		if(doc == null ) {
			throw new RuntimeException("null doc");
		}
			
		if(result == null) {
			throw new RuntimeException("null result");
		}
		
		
		try {
			Element shopRateElement = doc.select("div.shop-rate").first();
			fillGrade(shopRateElement, result);
			
			Element ulTargetElement = getSellerAndBuyer(doc);
			if(ulTargetElement == null) {
				throw new RuntimeException("ulTargetElement not found. doc: " + doc);
			} else {
				fillSellerGrade(ulTargetElement, result);
			}
			
		} catch (Exception e) {
			logger.error("parse doc failed. doc: " + doc.baseUri() +
					", cause: ", e);
		}
	}

	private static final int RATE_NUM = 3;
	private void fillGrade(Element shopRateElement, TaobaoShopParseResult result) throws Exception {
		Elements liElements = shopRateElement.select("li");
		if(liElements.size() != RATE_NUM) {
			throw new RuntimeException("ratenum doesn't match. shopRateElement: " + shopRateElement);
		}
		
		Map<String, String> propertyMap = new HashMap<String, String>();
		
		Element matchGradeElement = liElements.get(0);
		String matchGrade = matchGradeElement.select("em").first().text();
		propertyMap.put("matchGrade", matchGrade);
		
		Element serviceGradeElement = liElements.get(1);
		String serviceGrade = serviceGradeElement.select("em").first().text();
		propertyMap.put("serviceGrade", serviceGrade);
		
		Element speedGradeElement = liElements.get(2);
		String speedGrade = speedGradeElement.select("em").first().text();
		propertyMap.put("speedGrade", speedGrade);
		
		BeanUtils.populate(result, propertyMap);
	}
	
	private void fillSellerGrade(Element ulTargetElement, TaobaoShopParseResult result) throws Exception {
		boolean sellerFound = false;
		Map<String, String> propertyMap = new HashMap<String, String>();
		
		Elements creditElements = ulTargetElement.select("li");
		for(Element e : creditElements) {
			if("credit".equals(e.attr("class"))) {
				if(!sellerFound) {
					String sellerGrade = getGrade(e);
					String sellerGradePic = getGradePic(e);
					propertyMap.put("sellerGrade", sellerGrade);
					propertyMap.put("sellerGradePic", sellerGradePic);
					
					sellerFound = true;
					break;
				} 
			}
		}
		
		if(!sellerFound) {
			throw new RuntimeException("seller grade not found! element: " + ulTargetElement);
		}
		
		BeanUtils.populate(result, propertyMap);
	}
	
	private Element getSellerAndBuyer(Document doc) {
		/* <ul class="rate-summary clearfix"> */
		Element ulTargetElement = null;
		String targetToken = "rate-summary clearfix";
		Elements ulElements = doc.select("ul");
		for(Element e : ulElements) {
			if(targetToken.equals(e.attr("class"))) {
				ulTargetElement = e;
				break;
			}
		}
		
		return ulTargetElement;
	}
			
	private String getGrade(Element gradeElement) {
		Elements ahrefElements = gradeElement.select("a");
		if(ahrefElements.size() != 2) {
			throw new RuntimeException("ahrefElements' size not match. gradeElement: " + gradeElement);
		}
		
		Element jRadeElement = ahrefElements.get(0);
		return jRadeElement.text();
	}
	
	private static final String RANK_URL_BASE = "http://pics.taobaocdn.com/newrank/";
	private String getGradePic(Element gradeElement) {
		Elements ahrefElements = gradeElement.select("a");
		if(ahrefElements.size() != 2) {
			throw new RuntimeException("ahrefElements' size not match. gradeElement: " + gradeElement);
		}
		
		Element jPicElement = ahrefElements.get(1);
		Element picElemnt = jPicElement.select("img").first();
		
		String imgUrl = picElemnt.attr("src");
		if(!imgUrl.startsWith(RANK_URL_BASE)) {
			throw new RuntimeException("parse failed. element: " + picElemnt);
		}
		
		return imgUrl.substring(RANK_URL_BASE.length());
	}

	public static void main(String[] args) {
		String filePath = "D:\\work\\biqee\\test-pages\\taobao\\common\\common-shop-rate.html";
		InputStream in;
		TaobaoShopParseResult result = new TaobaoShopParseResult();
		try {
			in = new FileInputStream(filePath);
			TaobaoCShopRateParseServiceImpl parser = new TaobaoCShopRateParseServiceImpl();
			Document doc = JsoupUtil.createDocument(in, "gbk", "http://item.taobao.com/item.htm?id=2222538727&traclelog=jubuyoriprice");
			parser.parse(doc, result);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		
		String desc = ToStringBuilder.reflectionToString(result, ToStringStyle.MULTI_LINE_STYLE);
		System.out.println(desc);
	}

}
